$(function () {
    let JIM = new JMessage();
    let markId = getUrlString('markid');
    let username;
    let password;
    let gid = getUrlString('gid');
    let appkey,random_str,signature,timestamp,meUserFace,noMeUserFace = '../../res/img/messages/headPic.png',meNickName;

    //获取appid
    function getAppid() {
        layLoading();
        getData('post','/niu/apiv3/member_jmauth.php',{'markid':markId},function (data) {
            console.log(data);
            username = data.imid;
            password = data.impw;
            appkey = data.appkey;
            random_str = data.random_str;
            signature = data.signature;
            timestamp = data.timestamp;
            //调用初始化
            init();
        })
    }

    getAppid();

    //初始化
    function init() {
        JIM.init({
            "appkey" : appkey,
            "random_str" : random_str,
            "signature" : signature,
            "timestamp" : timestamp,
            "flag" : 1
        }).onSuccess(function(data) {
            console.log(data);
            login(username,password)
            //data.code 返回码
            //data.message 描述
        }).onFail(function(data) {
            codeError(data.code)
        });
    }

    //登录
    function login(userName,passWord) {

        JIM.login({
            'username' : userName,
            'password': passWord
        }).onSuccess(function(data) {
            console.log(data);
            //获取自己的信息
            getSelfInfo(username);
            //消息实时监听
            JIM.onMsgReceive(function(data) {
                console.log(data);
                var append = '';
                $(data.messages).each(function (index) {
                    if(this.content.msg_type === 'text'){
                        append +=
                            '      <li class="noMeLi chatListCommon">' +
                            '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                            '          <div class="pic">' +
                            '               <img src="'+noMeUserFace+'" alt="">' +
                            '          </div>' +
                            '       <div class="noMeNickName">'+this.content.from_name+'</div>'+
                            '          <div class="chatContent">' +
                            '               <img style="float: left;margin-left: -0.8rem;" src="../../res/img/messages/bsj.png" alt="">' +
                            '               <span>'+this.content.msg_body.text+'</span></div>' +
                            '      </li>'
                    }else if(this.content.msg_type === 'image'){
                        append +=
                            '<li class="noMeImgLi chatListCommon">' +
                            '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                            '                    <div class="pic">' +
                            '                        <img src="'+noMeUserFace+'" alt="">' +
                            '                    </div>' +
                            '       <div class="noMeNickName">'+this.content.from_name+'</div>'+
                            '                    <div class="chatContent">' +
                            '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                            '                        <img class="imgContent" src="../../res/img/eggTV/1.png" alt="">' +
                            '                    </div>' +
                            '                </li>';
                        getResource(this.content.msg_body.media_id).then(function(successData) {
                            $("#chatList .chatListCommon:last").find('.chatContent').find('.imgContent').attr('src',successData);
                        });
                    }else if(this.content.msg_type === 'file'){
                        let size = ((this.content.msg_body.fsize)/1024).toFixed(1);
                        append +=
                            '<li class="noMeFileLi chatListCommon">' +
                            '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                            '                    <div class="pic">' +
                            '                        <img src="'+noMeUserFace+'" alt="">' +
                            '                    </div>' +
                            '       <div class="noMeNickName">'+this.content.from_name+'</div>'+
                            '                    <a href="" class="chatContent">' +
                            '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                            '                        <p class="fileName">'+this.content.msg_body.fname+'</p>' +
                            '                        <p class="size">'+size+'MB</p>' +
                            '                    </a>' +
                            '                </li>';
                        getResource(this.content.msg_body.media_id).then(function(successData) {
                            $("#chatList .chatListCommon").eq(index).find('.chatContent').attr('href',successData);
                        });
                    }
                });
                $('#chatList').append(append);
                //聊天框默认最底部
                $(document).ready(function () {
                    $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
                });
            });


            JIM.onEventNotification(function(data) {
                console.log(data);
            });

            //离线消息同步监听
            JIM.onSyncConversation(function(data) {
                layer.closeAll('loading');
                console.log(data);
                let append = '';
                $(data).each(function () {
                    if(this.from_gid  === gid){
                        let messages = this.msgs;
                        $(messages).each(function (index) {
                            if(this.content.from_id === username){
                                if(this.content.msg_type === 'text'){
                                    append += '<li class="time">'+getTsFormatDate(this.content.create_time)+'</li>' +
                                        '      <li class="meLi chatListCommon">' +
                                        '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                                        '          <div class="pic">' +
                                        '               <img src="'+meUserFace+'" alt="">' +
                                        '          </div>' +
                                        '       <div class="meNickName">'+this.content.from_name+'</div>'+
                                        '          <div class="chatContent">' +
                                        '               <img style="float: right;margin-right: -0.8rem;" src="../../res/img/messages/hsj.png" alt="">' +
                                        '               <span>'+this.content.msg_body.text+'</span></div>' +
                                        '      </li>'
                                }else if(this.content.msg_type === 'image'){
                                    // getResource(this.content.msg_body.media_id);
                                    append += '<li class="time">'+getTsFormatDate(this.content.create_time)+'</li>' +
                                        '<li class="meImgLi chatListCommon">' +
                                        '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                                        '                    <div class="pic">' +
                                        '                       <img src="'+meUserFace+'" alt="">' +
                                        '                    </div>' +
                                        '       <div class="meNickName">'+this.content.from_name+'</div>'+
                                        '                    <div class="chatContent">' +
                                        '                        <img style="float: right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">'+
                                        '                        <img class="imgContent" src="../../res/img/eggTV/1.png" alt="">' +
                                        '                    </div>' +
                                        '                </li>';

                                    getResource(this.content.msg_body.media_id).then(function(successData) {
                                        $("#chatList .chatListCommon").eq(index).find('.chatContent').find('.imgContent').attr('src',successData);
                                    });
                                }else if(this.content.msg_type === 'file'){
                                    let size = ((this.content.msg_body.fsize)/1024).toFixed(1);
                                    append += '<li class="time">'+getTsFormatDate(this.content.create_time)+'</li>' +
                                        '<li class="meFileLi chatListCommon">' +
                                        '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                                        '                    <div class="pic">' +
                                        '                       <img src="'+meUserFace+'" alt="">' +
                                        '                    </div>' +
                                        '       <div class="meNickName">'+this.content.from_name+'</div>'+
                                        '                    <a href="" class="chatContent">' +
                                        '                        <img style="float: right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">'+
                                        '                        <p class="fileName">'+this.content.msg_body.fname+'</p>' +
                                        '                        <p class="size">'+size+'MB</p>' +
                                        '                    </a>' +
                                        '                </li>';
                                    getResource(this.content.msg_body.media_id).then(function(successData) {
                                        $("#chatList .chatListCommon").eq(index).find('.chatContent').attr('href',successData);
                                    });
                                }
                            }else {
                                if(this.content.msg_type === 'text'){
                                    append += '<li class="time">'+getTsFormatDate(this.content.create_time)+'</li>' +
                                        '      <li class="noMeLi chatListCommon">' +
                                        '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                                        '          <div class="pic">' +
                                        '               <img src="'+noMeUserFace+'" alt="">' +
                                        '          </div>' +
                                        '       <div class="noMeNickName">'+this.content.from_name+'</div>'+
                                        '          <div class="chatContent">' +
                                        '               <img style="float: left;margin-left: -0.8rem;" src="../../res/img/messages/bsj.png" alt="">' +
                                        '               <span>'+this.content.msg_body.text+'</span></div>' +
                                        '      </li>'
                                }else if(this.content.msg_type === 'image'){
                                    append += '<li class="time">'+getTsFormatDate(this.content.create_time)+'</li>' +
                                        '<li class="noMeImgLi chatListCommon">' +
                                        '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                                        '                    <div class="pic">' +
                                        '               <img src="'+noMeUserFace+'" alt="">' +
                                        '                    </div>' +
                                        '       <div class="noMeNickName">'+this.content.from_name+'</div>'+
                                        '                    <div class="chatContent">' +
                                        '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                                        '                        <img class="imgContent" src="../../res/img/eggTV/1.png" alt="">' +
                                        '                    </div>' +
                                        '                </li>';
                                    getResource(this.content.msg_body.media_id).then(function(successData) {
                                        $("#chatList .chatListCommon").eq(index).find('.chatContent').find('.imgContent').attr('src',successData);
                                    });
                                }else if(this.content.msg_type === 'file'){
                                    let size = ((this.content.msg_body.fsize)/1024).toFixed(1);
                                    append += '<li class="time">'+getTsFormatDate(this.content.create_time)+'</li>' +
                                        '<li class="noMeFileLi chatListCommon">' +
                                        '           <input type="hidden" class="msg_id" value="'+this.msg_id+'">'+
                                        '                    <div class="pic">' +
                                        '               <img src="'+noMeUserFace+'" alt="">' +
                                        '                    </div>' +
                                        '       <div class="noMeNickName">'+this.content.from_name+'</div>'+
                                        '                    <a href="" class="chatContent">' +
                                        '                        <img style="margin-left: -0.8rem;vertical-align: top" src="../../res/img/messages/bsj.png" alt="">' +
                                        '                        <p class="fileName">'+this.content.msg_body.fname+'</p>' +
                                        '                        <p class="size">'+size+'MB</p>' +
                                        '                    </a>' +
                                        '                </li>';
                                    getResource(this.content.msg_body.media_id).then(function(successData) {
                                        $("#chatList .chatListCommon").eq(index).find('.chatContent').attr('href',successData);
                                    });
                                }
                            }

                        })
                    }
                });
                $('#chatList').append(append);

                //聊天框默认最底部
                $(document).ready(function () {
                    $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
                });

            });

            JIM.onUserInfUpdate(function(data) {
                console.log('onUserInfUpdate : ' + JSON.stringify(data));
            });

            JIM.onSyncEvent(function(data) {
                console.log('onSyncEvent : ' + JSON.stringify(data));
            });

            JIM.onMsgReceiptChange(function(data){
                console.log('onMsgReceiptChange : ' + JSON.stringify(data));

            });

            JIM.onSyncMsgReceipt(function(data){
                console.log('onSyncMsgReceipt : ' + JSON.stringify(data));

            });

            JIM.onMutiUnreadMsgUpdate(function(data){
                console.log('onConversationUpdate : ' + JSON.stringify(data));

            });

            JIM.onTransMsgRec(function(data){
                console.log('onTransMsgRec : ' + JSON.stringify(data));
            });

            JIM.onRoomMsg (function(data){
                console.log('onRoomMsg  : ' + JSON.stringify(data));
            });





        }).onFail(function(data) {
            codeError(data.code)
        }).onTimeout(function(data) {
            console.log('timeout:' + JSON.stringify(data));
        });
    }


    //发送群聊消息
    $('#messageBtn').click(function () {
        let content = $('#messageInput').html();
        if(content === ''){
            laymsg('发送内容不能为空');
            return
        }
        sendGroupMsg(content)
    });

    //群聊消息
    function sendGroupMsg(content) {
        //var gid = theGid
        JIM.sendGroupMsg({
            'target_gid' : gid,
            'content' : content,
            'need_receipt':true
        }).onSuccess(function(data,msg) {
            console.log(data);
            if(data.code === 0){
                $('#messageInput').html('');
                var append = '<li class="time">'+getTsFormatDate(data.ctime_ms)+'</li>' +
                    '      <li class="meLi chatListCommon">' +
                    '          <div class="pic">' +
                    '               <img src="'+meUserFace+'" alt="">' +
                    '          </div>' +
                    '          <div class="meNickName">'+meNickName+'</div>'+
                    '          <div class="chatContent">' +
                    '               <img style="float: right;margin-right: -0.8rem;" src="../../res/img/messages/hsj.png" alt="">' +
                    '               <span>'+msg.content.msg_body.text+'</span></div>' +
                    '      </li>'
            }
            $('#chatList').append(append);
            $(document).ready(function () {
                $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
            });
        }).onFail(function(data) {
            codeError(data.code)
        });
    }

    //群聊图片
    function sendGroupPic(fd) {
        JIM.sendGroupPic({
            'target_gid' : gid,
            'image' : fd,
            'nead_receipt':true
        }).onSuccess(function(data,msg) {
            if(data.code === 0){
                //发送成功之后为空
                $('#inputImage1,#inputImage2,#inputImage3').val('');
                getResource(msg.content.msg_body.media_id).then(function(successData) {
                    var append = '<li class="time">'+getTsFormatDate(data.ctime_ms)+'</li>' +
                        '                <li class="meImgLi chatListCommon">' +
                        '                    <div class="pic">' +
                        '                        <img src="'+meUserFace+'" alt="">' +
                        '                    </div>' +
                        '          <div class="meNickName">'+meNickName+'</div>'+
                        '                    <div class="chatContent">' +
                        '                        <img style="float:right;margin-right: -0.8rem;vertical-align: top" src="../../res/img/messages/hsj.png" alt="">' +
                        '                        <img class="imgContent" src="'+successData+'" alt="">' +
                        '                    </div>' +
                        '                </li>';
                    $('#chatList').append(append);
                    $('#sendPicBtn,#noSendPicBtn,#preview').hide();
                    let indexBottomHeight = $('.indexBottom').height();
                    let indexChatWrapHeight = indexChatHeight - indexBottomHeight - 30;
                    $('.indexChatWrap,.chatList').css('height',indexChatWrapHeight);
                    $(document).ready(function () {
                        $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
                    });
                });

            }
        }).onFail(function(data) {
            codeError(data.code)
        });
    }

    //调用相册发送单聊图片
    $('#inputImage1').on('change',function () {
        let fd = new FormData();
        let file;
        file = document.getElementById('inputImage1');
        fd.append(file.files[0].name, file.files[0]);
        sendGroupPic(fd)
    });

    //调用相机发送单聊图片
    $('#inputImage2').on('change',function () {
        let fd = new FormData();
        let file;
        file = document.getElementById('inputImage2');
        fd.append(file.files[0].name, file.files[0]);
        sendGroupPic(fd)
    });

    //调用发送文件
    $('#inputImage3').on('change',function () {
        let fd = new FormData();
        let file;
        file = document.getElementById('inputImage3');
        console.log(file.files[0]);
        if(!file.files[0]) {
            laymsg('发送失败');
        }
        fd.append(file.files[0].name, file.files[0]);
        sendGroupFile(fd)
    });

    function sendGroupFile(fd) {
        JIM.sendGroupFile({
            'target_gid' : gid,
            'file' : fd,
            'nead_receipt':true
        }).onSuccess(function(data,msg) {
            // console.log(data);
            // console.log(msg);
            $('#inputImage3').val('');
            getResource(msg.content.msg_body.media_id).then(function(successData) {
                console.log(successData);
                let size = ((msg.content.msg_body.fsize)/1024).toFixed(1);
                let append = '<li class="time">'+getTsFormatDate(data.ctime_ms)+'</li>' +
                    '<li class="meFileLi chatListCommon">' +
                    '                    <div class="pic">' +
                    '                        <img src="'+meUserFace+'" alt="">' +
                    '                    </div>' +
                    '          <div class="meNickName">'+meNickName+'</div>'+
                    '                    <a href="'+successData+'" class="chatContent">' +
                    '                        <img style="float: right;margin-right: -0.8rem;" src="../../res/img/messages/hsj.png" alt="">' +
                    '                        <p class="fileName">'+msg.content.msg_body.fname+'</p>' +
                    '                        <p class="size">'+size+'MB</p>' +
                    '                    </a>' +
                    '                </li>';
                $('#chatList').append(append);
                $('#sendPicBtn,#noSendPicBtn,#preview').hide();
                let indexBottomHeight = $('.indexBottom').height();
                let indexChatWrapHeight = indexChatHeight - indexBottomHeight - 30;
                $('.indexChatWrap,.chatList').css('height',indexChatWrapHeight);
                $(document).ready(function () {
                    $(".chatList").scrollTop($(".chatList")[0].scrollHeight);
                });
            });
        }).onFail(function(data) {
            codeError(data.code)
        });
    }

    //获取用户的个人信息
    function getSelfInfo(username) {
        JIM.getUserInfo({
            'username' : username
        }).onSuccess(function(data) {
            // console.log(data);
            meNickName = data.user_info.nickname;
            getResource(data.user_info.avatar).then(function(successData) {
                meUserFace = successData;
                $('#chatList .meLi .pic img,#chatList .meImgLi .pic img,#chatList .meFileLi .pic img').attr('src',successData)
            })

        }).onFail(function(data) {
            codeError(data.code)
            console.log(data);
        });

    }

    //获取图片资源
    function getResource (media_id) {
        return new Promise(function(success,fail) {
            JIM.getResource({
                'media_id' : media_id,
            }).onSuccess(function(data) {
                // console.log(data);
                success(data.url)
                //data.code 返回码
                //data.message 描述
                //data.url 资源临时访问路径，具体超时时间expire time会包含在url中
            }).onFail(function(data) {
                codeError(data.code)
                //data.code 返回码
                //data.message 描述
            });
        });
    }
});